// index.js
Page({
  data: {
    headerArr: ["/imgs/header1.png", "/imgs/header2.png", "/imgs/header3.png", "/imgs/header4.png", "/imgs/header5.png", "/imgs/header6.png", "/imgs/header7.png", "/imgs/header8.png", "/imgs/header9.png", "/imgs/header10.png", "/imgs/header11.png", "/imgs/header12.png", "/imgs/header13.png", "/imgs/header14.png", "/imgs/header15.png", "/imgs/header16.png", "/imgs/header17.png", "/imgs/header18.png", "/imgs/header19.png", "/imgs/header20.png", "/imgs/header21.png", "/imgs/header22.png", "/imgs/header23.png", "/imgs/header24.png", "/imgs/header25.png", "/imgs/header26.png", "/imgs/header27.png", "/imgs/header28.png", "/imgs/header29.png", "/imgs/header30.png", "/imgs/header31.png", "/imgs/header32.png"],
    headerIndex: 0,
    wallpaperIndex: 0,
    showItem: 'wallpaper', //显示类目
    wallpaperArr: ['/imgs/bz1.jpg', '/imgs/bz2.jpg', '/imgs/bz3.jpg'],
    currentWallpaper: '/imgs/bz1.jpg',
  },
  // 选择本地图片
  chooseImage() {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log(res);
        // tempFilePath可以作为img标签的src属性显示图片
        // const tempFilePaths = res.tempFilePaths
        that.setData({
          currentWallpaper: res.tempFilePaths[0]
        })
      }
    })
  },
  // 选中壁纸样式
  chooseStyle(e) {
    let attr = e.currentTarget.dataset.attr;
    let index = e.currentTarget.dataset.index;
    this.setData({
      [attr]: index
    });
    console.log(attr)
    if (attr == 'wallpaperIndex') {
      let wallpaperArr = this.data.wallpaperArr;
      this.setData({
        currentWallpaper: wallpaperArr[index]
      })
    }
  },
  // 根据图片路径获取图片宽高
  getImgInfo(url, callback) {
    wx.getImageInfo({
      src: url,
      success(res) {
        if (callback) callback(res)
      },
      fail(res) {
        console.log(res);
        wx.showToast({
          title: '图片错误',
          duration: 1500,
          icon: ''
        })
      }
    })
  },
  // 显示修改类目
  replaceWallpaper(e) {
    //wallpaper：显示底部壁纸，header：显示修改头部样式
    let showItem = this.data.showItem;
    let e_showItem = e.currentTarget.dataset.showitem;
    if (showItem == 'header' && e_showItem == 'header') {
      showItem = 'hideMenu'
    } else {
      showItem = e_showItem
      if (e_showItem == 'wallpaper' && !this.data.currentWallpaper) {
        let wallpaperArr = this.data.wallpaperArr;
        let wallpaperIndex = this.data.wallpaperIndex;
        this.setData({
          currentWallpaper: wallpaperArr[wallpaperIndex]
        })
      }
    };
    this.setData({
      showItem
    });
  },
  // 下载图片
  async downloadImg() {
    wx.showLoading({
      title: '加载中...'
    });
    let that = this;
    let dwidth = wx.getSystemInfoSync().windowWidth // 获取当前窗口的宽度
    let dheight = wx.getSystemInfoSync().windowHeight // 获取当前窗口的高度
    let headerIndex = this.data.headerIndex;
    let headerImg = this.data.headerArr[headerIndex]; //头部图片
    let currentWallpaper = this.data.currentWallpaper; //底部背景
    this.setData({
      canvasWidth: dwidth,
      canvasHeight: dheight
    });
    const ctx = wx.createCanvasContext('mycanvas');
    // 填充背景
    ctx.fillStyle = "#FFFFFF";
    ctx.fillRect(0, 0, dwidth, dheight);
    //根据背景图片裁剪伸缩适配屏幕
    this.getImgInfo(currentWallpaper, (res) => {
      let w = res.width;
      let h = res.height;
      let dw = dwidth / w;
      let dh = dheight / h;
      // 裁剪中间部分，图片大于或都小于canvas
      if (w > dwidth && h > dheight || w < dwidth && h < dheight) {
        if (dw > dh) {
          ctx.drawImage(currentWallpaper, 0, (h - dheight / dw) / 2, w, dheight / dw, 0, 0, dwidth, dheight)
        } else {
          ctx.drawImage(currentWallpaper, (w - dwidth / dh) / 2, 0, dwidth / dh, h, 0, 0, dwidth, dheight)
        }
      }
      // 拉伸图片
      else {
        if (w < dwidth) {
          ctx.drawImage(currentWallpaper, 0, (h - dheight / dw) / 2, w, dheight / dw, 0, 0, dwidth, dheight)
        } else {
          ctx.drawImage(currentWallpaper, (w - dwidth / dh) / 2, 0, dwidth / dh, h, 0, 0, dwidth, dheight)
        }
      };
      //顶部图片只做横向拉伸伸缩
      this.getImgInfo(headerImg, (res) => {
        let w1 = res.width;
        let h1 = res.height;
        let dw1 = dwidth / w1;
        ctx.drawImage(headerImg, 0, 0, w1 * dw1, h1 * dw1)
        ctx.draw(false, setTimeout(() => {
          wx.canvasToTempFilePath({
            canvasId: 'mycanvas',
            success: function (res) {
              that.setData({
                canvasImagePath: res.tempFilePath
              });
              that.savePoster();
            },
            fail: function (res) {
              console.log('fail', res);
            }
          });
        }, 300));
      });
    });
  },
  // 开始保存海报至相册
  savePoster() {
    let that = this;
    //判断当前小程序是否有保存相册的权限
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success(res) {
              that.startSaveImage();
            },
            fail() { //这里是用户拒绝授权后的回调
              wx.hideLoading();
              wx.showModal({
                content: '请允许相册权限,拒绝将无法正常使用小程序',
                showCancel: false,
                success() {
                  wx.openSetting({
                    success(settingdata) {
                      if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                        that.startSaveImage();
                      } else {
                        console.log("获取权限失败")
                      }

                    }
                  })
                }
              })
            }
          })
        } else {
          that.startSaveImage();
        }
      }
    })
  },
  // 确认开启相册权限，canvas绘画完成，canvas生成图片完成
  startSaveImage() {
    let that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.canvasImagePath,
      success(res) {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 1500
        })
      },
      fail(err) {
        wx.showToast({
          title: '保存失败',
          icon: 'error',
          duration: 1500
        })
        console.log('err', err);
      }
    });
  },
  // 分享
  onShareAppMessage(e) {
    //自定义转发内容
    var title = "壁纸修改器"
    return {
      title: title,
      path: "/pages/index/index",
      success: function (res) {
        wx.showToast({
          title: '分享成功',
          icon: 'none',
          duration: dwidth0
        })
      },
      fail: function (res) {
        wx.showToast({
          title: '分享失败',
          icon: 'none',
          duration: dwidth0
        })
      }
    }
  },
  onLoad() {

  }
})